package com.example.sell_qq;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.example.sell_qq.fragment.HomeFragment;
import com.example.sell_qq.fragment.SaleFragment;

public class MainActivity extends AppCompatActivity implements BottomNavigationBar.OnTabSelectedListener {

    // 底部导航栏
    BottomNavigationBar mBottomNavigationBar;

    // 首页分片
    private HomeFragment mHomeFragment;
    // 卖号分片
    private SaleFragment mSaleFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initEvent();
    }

    /**
     * 初始化底部导航栏(增加 首页/卖号)
     */
    private void initView() {
        mBottomNavigationBar = findViewById(R.id.bottom_navigation_bar);
        mBottomNavigationBar.addItem(
                new BottomNavigationItem(R.drawable.home, getString(R.string.home))
                        .setActiveColorResource(R.color.colorAccent)
        )
                .addItem(
                        new BottomNavigationItem(R.drawable.sale, getString(R.string.sale))
                                .setActiveColorResource(R.color.colorAccent)
                )
                .initialise();
    }

    /**
     * 初始化 默认页(首页)
     */
    private void initEvent() {
        mBottomNavigationBar.setTabSelectedListener(this);
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.replace(R.id.fragment_container, new HomeFragment());
        transaction.commit();
    }

    /**
     * 底部导航栏事件
     *
     * @param position 所选的tab在bottomNavigation中的位置
     */
    @Override
    public void onTabSelected(int position) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        switch (position) {
            case 0:
                if (mHomeFragment == null) {
                    mHomeFragment = new HomeFragment();
                }
                transaction.replace(R.id.fragment_container, mHomeFragment);
                break;
            case 1:
                if (mSaleFragment == null) {
                    mSaleFragment = new SaleFragment();
                }
                transaction.replace(R.id.fragment_container, mSaleFragment);
                break;
        }
        transaction.commit();
    }

    @Override
    public void onTabUnselected(int position) {
    }

    @Override
    public void onTabReselected(int position) {
    }

}
